<?php


namespace app\common\model;


use app\common\enum\MainEnum;
use app\common\exception\LogicException;
use app\common\service\rabbitMQ\RabbitMQBusinessInterface;
use app\common\service\rabbitMQ\UserCouponExpiredCheck;

class UserCouponModel extends CommonModel
{
    protected $name = 'user_coupon';

    public static function onAfterWrite($model)
    {
        /**
         * 'user_id' => int 2
         * 'coupon_id' => int 3
         * 'status' => int 0
         * 'start_time' => int 1608301292
         * 'end_time' => int 1608387692
         */
        if ($model->getData('status') === MainEnum::COUPON_USER_STATUS['待使用']) {
            $expireTimestamp = strtotime($model->getData('end_time')) - time();
            if ($expireTimestamp <= 0) {
                throw new LogicException(['msg' => '优惠券时间有误']);
            }
            UserCouponExpiredCheck::publisher(
                [
                    'id'               => $model->getData('id'),
                    'expire_timestamp' => $expireTimestamp * 1000,
                ],
                $expireTimestamp * 1000
            );
        }
    }

    public function setStatusAttr($v, $data)
    {
        return $v;
    }

    public function getExtendStartTimeAttr($v, $data)
    {
        $timestamp = strtotime($data['start_time']);
        return date('Y-m-d', $timestamp);
    }

    public function getExtendEndTimeAttr($v, $data)
    {
        $timestamp = strtotime($data['end_time']);
        return date('Y-m-d', $timestamp);
    }

    public function getExtendExpireSoonAttr($v, $data)
    {
        $timestamp = strtotime($data['end_time']) - NOW_TIME;
        if ($timestamp > 3600 * 24) {
            return null;
        }
        return $timestamp;
    }

    public function setStartTimeAttr($timestamp)
    {
        return date('Y-m-d H:i:s', $timestamp);
    }

    public function setEndTimeAttr($timestamp)
    {
        return date('Y-m-d H:i:s', $timestamp);
    }

    public function setUseTimeAttr($timestamp)
    {
        return date('Y-m-d H:i:s', $timestamp);
    }

    public function getExtendStatusTextAttr($v, $data): ?string
    {
        foreach (MainEnum::COUPON_USER_STATUS as $key => $item) {
            if ($data['status'] === $item) {
                return $key;
            }
        }
        return '';
    }

    public function couponInfo()
    {
        return $this->hasOne(CouponModel::class, 'id', 'coupon_id');
    }

    public function getUserCouponList($user_id)
    {
        return $this->with(
            [
                'couponInfo.products',
            ]
        )->order(
            [
                'create_time' => 'desc',
            ]
        )->where('user_id', $user_id)->append(
            [
                'extend_start_time',
                'couponInfo' => [
                    'extend_desc',
                    'extend_type_text',
                ],
                'extend_end_time',
                'extend_expire_soon',
                'extend_status_text',
            ]
        )->select();
    }

    public function getUserCoupon($where = [])
    {
        return $this->with(
            [
                'couponInfo.products',
            ]
        )->order(
            [
                'create_time' => 'desc',
            ]
        )->where($where)->append(
            [
                'extend_start_time',
                'couponInfo' => [
                    'extend_desc',
                    'extend_type_text',
                ],
                'extend_end_time',
                'extend_expire_soon',
                'extend_status_text',
            ]
        )->find();
    }

    public static function okUse($couponArr, $productIds = [], $priceTotal = 0)
    {
        //判断状态
        if ($couponArr['status'] !== MainEnum::COUPON_USER_STATUS['待使用']) {
            return false;
        }
        if (strtotime($couponArr['start_time']) >= NOW_TIME) {
            #未开始
            return false;
        }
        if (strtotime($couponArr['end_time']) <= NOW_TIME) {
            #已过期
            return false;
        }

        //判断商品
        if ($couponArr['couponInfo']['all_product'] !== true && !empty($productIds)) {
            #部分商品可用
            $allowProductIds = [];
            foreach ($couponArr['couponInfo']['products'] as $item) {
                $allowProductIds[] = $item['product_id'];
            }

            foreach ($productIds as $product_id) {
                if (!in_array($product_id, $allowProductIds, true)) {
                    return false;
                }
            }
        }

        return !($couponArr['couponInfo']['use_min_price'] > $priceTotal);
    }
}